package com.princess.demok.ui.demo

import android.Manifest
import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.*
import android.net.wifi.*
import android.net.wifi.p2p.WifiP2pManager
import android.os.Build
import android.provider.Settings
import androidx.recyclerview.widget.LinearLayoutManager
import com.princess.baselib.utils.LogUtils
import com.princess.baselib.utils.setOnClickListenerWithTrigger
import com.princess.baselib.utils.showToast
import com.princess.demok.R
import com.princess.demok.base.view.MyBaseActivity
import com.princess.demok.ui.adapter.WifiListAdapter
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_wifi_demo.*
import kotlinx.android.synthetic.main.layout_recycler_just.*
import kotlinx.coroutines.launch


/**
 * @author: W9072388
 * @date: 2021/11/26
 * @Description:
 */
class WifiDemoActivity : MyBaseActivity() {

    var mWifiManager: WifiManager? = null

    var isHavePermissions = false

    var isSearch = false
    var connectivityManager: ConnectivityManager? = null

    var isSuggestion = true

    var suggestion2: WifiNetworkSuggestion? = null


    override fun getLayoutId(): Int = R.layout.activity_wifi_demo

    private val wifiListAdapter by lazy {
        WifiListAdapter()
    }


    @SuppressLint("WifiManagerLeak")
    override fun initOnCreate() {
        val intentFilter = IntentFilter()
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)
        val intentFilterConnection =
            IntentFilter(WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION);
        registerReceiver(wifiScanReceiver, intentFilter)
        registerReceiver(broadcastReceiver, intentFilterConnection);

        mWifiManager = getSystemService(Context.WIFI_SERVICE) as WifiManager

        connectivityManager =
            getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager

        checkWifiState()

        setPermissions()

        setAdapter()
    }

    //获取wifi信息
    private fun getWifiInfo() {
        launch {
            val wifiInfo = mWifiManager?.connectionInfo
            val networkId = wifiInfo?.networkId
            if (networkId == -1) {
                LogUtils.i("wifi连接未成功，请重新连接")
                return@launch
            }
            val ssid = wifiInfo?.ssid
            val bssid = wifiInfo?.bssid
            LogUtils.i("当前连接ssid $ssid")
            val list = wifiListAdapter.data
            var scanResult: ScanResult? = null
            list.forEach {
                if (it.SSID == ssid) {
                    scanResult = it
                }
            }
            scanResult?.let {
                list.remove(it)
                list.add(0, it)
            }
            if (bssid != null) {
                wifiListAdapter.bssid = bssid
            }
            wifiListAdapter.setList(list)
        }
    }

    fun setAdapter() {
        mRecyclerView.layoutManager = LinearLayoutManager(this)
        mRecyclerView.adapter = wifiListAdapter

        wifiListAdapter.setOnItemClickListener { adapter, view, position ->
            val scanResult = adapter.getItem(position) as ScanResult
            if (scanResult.BSSID == wifiListAdapter.bssid) {
//                if (isSuggestion) {
                setUnConnect(scanResult.SSID)
//                } else {
//                setUnconnectForSpecifier(scanResult)
//                }
            } else {
                if (wifiListAdapter.bssid.isNotEmpty()) {
                    setUnConnect(scanResult.SSID)
                }
//                if (isSuggestion) {
                connectWifi(scanResult, edtWifiDemo.text.toString())
//                } else {
//                connectWifiForSpecifier(scanResult, edtWifiDemo.text.toString())
//                }
            }


        }
    }

    //断开连接点对点直连
    private fun setUnconnectForSpecifier(scanResult: ScanResult) {
        connectivityManager?.unregisterNetworkCallback(networkCallback)
        connectivityManager?.bindProcessToNetwork(null);
        wifiListAdapter.bssid = ""
        wifiListAdapter.notifyDataSetChanged()
    }


    val networkCallback = object : ConnectivityManager.NetworkCallback() {

        override fun onAvailable(network: Network) {
            // do success processing here..
            LogUtils.i("wifi处理成功")
            connectivityManager?.bindProcessToNetwork(network);
            getWifiInfo()
        }

        override fun onUnavailable() {
            // do failure processing here..
            LogUtils.i("wifi处理失败")
        }

    }

    //断开连接
    @SuppressLint("NotifyDataSetChanged", "MissingPermission")
    private fun setUnConnect(ssid: String) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val status = if (suggestion2 == null) {
                mWifiManager?.removeNetworkSuggestions(arrayListOf())
            } else {
                val suggestionsList = listOf(suggestion2)
                mWifiManager?.removeNetworkSuggestions(suggestionsList)
            }

            if (status != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
                LogUtils.i("do error handling here $status")
            }
            LogUtils.i("断开连接 $ssid")
            wifiListAdapter.bssid = ""
            wifiListAdapter.notifyDataSetChanged()
        } else {
            if (mWifiManager?.disconnect() == true) {
                LogUtils.i("断开wifi成功")
            } else {
                LogUtils.i("断开wifi失败")
            }
        }
    }

    //通过建议连接wifi
    @SuppressLint("WifiManagerLeak", "MissingPermission")
    private fun connectWifi(scanResult: ScanResult, password: String) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            suggestion2 = WifiNetworkSuggestion.Builder()
                .setSsid(scanResult.SSID)
                .setBssid(MacAddress.fromString(scanResult.BSSID))
                .setWpa2Passphrase(password)
                .setIsAppInteractionRequired(true) // Optional (Needs location permission)
                .build()

            val suggestionsList = listOf(suggestion2)

            val status = mWifiManager?.addNetworkSuggestions(suggestionsList);
            if (status != WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS) {
                // do error handling here
                LogUtils.i("do error handling here $status")
            }
            LogUtils.i("获取连接回调")
            getWifiInfo()
        } else {
            val ssid = scanResult.SSID
            val localWifiConfiguration = WifiConfiguration()
            //公认的IEEE 802.11验证算法。

            localWifiConfiguration.allowedAuthAlgorithms.clear()
            localWifiConfiguration.allowedAuthAlgorithms.set(0)
            //公认的的公共组密码。

            localWifiConfiguration.allowedGroupCiphers.clear()
            localWifiConfiguration.allowedGroupCiphers.set(2)
            //公认的密钥管理方案。

            localWifiConfiguration.allowedKeyManagement.clear()
            localWifiConfiguration.allowedKeyManagement.set(1)
            //密码为WPA。

            localWifiConfiguration.allowedPairwiseCiphers.clear()
            localWifiConfiguration.allowedPairwiseCiphers.set(1)
            localWifiConfiguration.allowedPairwiseCiphers.set(2)
            //公认的安全协议。

            localWifiConfiguration.allowedProtocols.clear()

            localWifiConfiguration.SSID = "\"" + ssid + "\""
            localWifiConfiguration.preSharedKey = "\"" + password + "\""
            //不广播其SSID的网络

            localWifiConfiguration.hiddenSSID = true
            val wcnetWorkid = mWifiManager?.addNetwork(localWifiConfiguration);
            if (wcnetWorkid != null) {
                val connect = mWifiManager?.enableNetwork(wcnetWorkid, true)
                if (connect == true) {
                    LogUtils.i("wifi连接成功")
                } else {
                    LogUtils.i("wifi连接失败")
                }
            }
        }
    }

    //通过点对点连接wifi
    @SuppressLint("WifiManagerLeak")
    private fun connectWifiForSpecifier(scanResult: ScanResult, password: String) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            val specifier = WifiNetworkSpecifier.Builder()
                .setSsid(scanResult.SSID)
                .setBssid(MacAddress.fromString(scanResult.BSSID))
                .setWpa2Passphrase(password)
                .build()
            val request = NetworkRequest.Builder()
                .addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
                .removeCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
                .setNetworkSpecifier(specifier)
                .build()

            connectivityManager?.requestNetwork(request, networkCallback)

        } else {
            val ssid = scanResult.SSID
            val localWifiConfiguration = WifiConfiguration()
            //公认的IEEE 802.11验证算法。

            localWifiConfiguration.allowedAuthAlgorithms.clear()
            localWifiConfiguration.allowedAuthAlgorithms.set(0)
            //公认的的公共组密码。

            localWifiConfiguration.allowedGroupCiphers.clear()
            localWifiConfiguration.allowedGroupCiphers.set(2)
            //公认的密钥管理方案。

            localWifiConfiguration.allowedKeyManagement.clear()
            localWifiConfiguration.allowedKeyManagement.set(1)
            //密码为WPA。

            localWifiConfiguration.allowedPairwiseCiphers.clear()
            localWifiConfiguration.allowedPairwiseCiphers.set(1)
            localWifiConfiguration.allowedPairwiseCiphers.set(2)
            //公认的安全协议。

            localWifiConfiguration.allowedProtocols.clear()

            localWifiConfiguration.SSID = "\"" + ssid + "\""
            localWifiConfiguration.preSharedKey = "\"" + password + "\""
            //不广播其SSID的网络

            localWifiConfiguration.hiddenSSID = true
            val wcnetWorkid = mWifiManager?.addNetwork(localWifiConfiguration);
            if (wcnetWorkid != null) {
                val connect = mWifiManager?.enableNetwork(wcnetWorkid, true)
                if (connect == true) {
                    LogUtils.i("wifi连接成功")
                } else {
                    LogUtils.i("wifi连接失败")
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(wifiScanReceiver)
        unregisterReceiver(broadcastReceiver)
//        connectivityManager?.unregisterNetworkCallback(networkCallback)
    }

    @SuppressLint("CheckResult")
    private fun setPermissions() {
        RxPermissions(this)
            .request(
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.CHANGE_WIFI_STATE
            )
            .subscribe { aBoolean ->
                if (aBoolean) {
                    showToast("获取权限成功")
                    isHavePermissions = true
                } else {
                    btnSearchWifiDemo.text = "点击再次获取权限"
                    isHavePermissions = false
                }
            }
    }

    override fun initOnClickerListener() {
        super.initOnClickerListener()
        btnSearchWifiDemo.setOnClickListenerWithTrigger {
            if (isHavePermissions) {
                searchWifi()
            } else {
                setPermissions()
            }
        }

        btnStateWifiDemo.setOnClickListenerWithTrigger {
            if (btnStateWifiDemo.isSelected) {//打开状态
                closeWifi()
            } else {
                openWifi()
            }
        }
    }

    private fun openWifi() {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
            mWifiManager?.isWifiEnabled = true
        } else {
            openWifiSet();
        }
    }

    /**
     * 打开wifi设置页码
     */
    private fun openWifiSet() {
        startActivity(Intent(Settings.ACTION_WIFI_SETTINGS));
    }

    fun closeWifi() {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.P) {
            mWifiManager?.isWifiEnabled = false
        } else {
            openWifiSet();
        }
    }


    @SuppressLint("WifiManagerLeak", "SetTextI18n")
    private fun searchWifi() {
        if (isSearch) {
            isSearch = false
        }
        isSuggestion = !isSuggestion
        btnSearchWifiDemo.text = "搜索中...isSuggestion  $isSuggestion"
        val success = mWifiManager?.startScan()
        if (!success!!) {
            // scan failure handling
            scanFailure()
        }

    }

    val TAG = "wifi"
    val wifiScanReceiver = object : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            when (intent.action) {
                WifiManager.WIFI_STATE_CHANGED_ACTION -> {
                    when (intent.getIntExtra(
                        WifiManager.EXTRA_WIFI_STATE,
                        WifiManager.WIFI_STATE_UNKNOWN
                    )) {
                        WifiManager.WIFI_STATE_ENABLING ->
                            LogUtils.i(TAG, "onReceive: 正在打开 WIFI...");
                        WifiManager.WIFI_STATE_ENABLED -> {
                            LogUtils.i(TAG, "onReceive: WIFI 已打开")
                            getWifiInfo()
                        }

                        WifiManager.WIFI_STATE_DISABLING ->
                            LogUtils.i(TAG, "onReceive: 正在关闭 WIFI...");
                        WifiManager.WIFI_STATE_DISABLED ->
                            LogUtils.i(TAG, "onReceive: WIFI 已关闭");
                        else ->
                            LogUtils.i(TAG, "onReceive: WIFI 状态未知!");

                    }
                }
                WifiManager.SCAN_RESULTS_AVAILABLE_ACTION -> {
                    val success = intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false)
                    LogUtils.i(TAG, "onReceive: WIFI扫描  " + if (success) "完成" else "未完成")
                    if (success) {
                        scanSuccess()
                    } else {
                        scanFailure()
                    }
                }
            }

        }
    }

    val broadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            if (intent?.action == WifiManager.ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION) {
                LogUtils.i("ACTION_WIFI_NETWORK_SUGGESTION_POST_CONNECTION")
                getWifiInfo()
            }
        }
    }


    /**
     * A BroadcastReceiver that notifies of important Wi-Fi p2p events.
     */
    class WiFiDirectBroadcastReceiver(
        private val manager: WifiP2pManager,
        private val channel: WifiP2pManager.Channel
    ) : BroadcastReceiver() {

        override fun onReceive(context: Context, intent: Intent) {
            val action: String? = intent.action
            when (action) {
                WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION -> {
                    // Check to see if Wi-Fi is enabled and notify appropriate activity
                }
                WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION -> {
                    // Call WifiP2pManager.requestPeers() to get a list of current peers
                }
                WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION -> {
                    // Respond to new connection or disconnections
                }
                WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION -> {
                    // Respond to this device's wifi state changing
                }
            }
        }
    }

    fun checkWifiState() {
        when (mWifiManager?.wifiState) {
            WifiManager.WIFI_STATE_ENABLING ->
                LogUtils.i(TAG, "onReceive: 正在打开 WIFI...");
            WifiManager.WIFI_STATE_ENABLED -> {
                LogUtils.i(TAG, "onReceive: WIFI 已打开");
                btnStateWifiDemo.text = "关闭"
                btnStateWifiDemo.isSelected = true

                getWifiInfo()
            }
            WifiManager.WIFI_STATE_DISABLING ->
                LogUtils.i(TAG, "onReceive: 正在关闭 WIFI...");
            WifiManager.WIFI_STATE_DISABLED -> {
                btnStateWifiDemo.text = "打开"
                LogUtils.i(TAG, "onReceive: WIFI 已关闭");
                btnStateWifiDemo.isSelected = false
            }

            else ->
                LogUtils.i(TAG, "onReceive: WIFI 状态未知!");
        }
    }

    private fun scanSuccess() {
        if (isSearch) return
        var results = mWifiManager?.scanResults

        val list = arrayListOf<ScanResult>()
        results?.forEach {
            if (it.SSID.contains("ZAIN_")) {
                list.add(0, it)
            } else if (it.SSID.contains("ZAIN", true) || it.SSID.contains("OPPO", true)) {
                list.add(it)
            }
        }

        LogUtils.i("搜索成功")
        LogUtils.i("数据", list.toString())
        btnSearchWifiDemo.text = "搜索完成...isSuggestion  $isSuggestion"
        wifiListAdapter.setList(list)
        isSearch = true
    }

    private fun scanFailure() {
        if (isSearch) return
        // handle failure: new scan did NOT succeed
        // consider using old scan results: these are the OLD results!
        var results = mWifiManager?.scanResults

        val list = arrayListOf<ScanResult>()
        results?.forEach {
            if (it.SSID.contains("ZAIN_")) {
                list.add(0, it)
            } else if (it.SSID.contains("ZAIN", true) || it.SSID.contains("OPPO", true)) {
                list.add(it)
            }
        }

        LogUtils.i("搜索失败，获取历史数据集")
        LogUtils.i("数据", list.toString())
        btnSearchWifiDemo.text = "搜索完成...isSuggestion  $isSuggestion"
        wifiListAdapter.setList(list)
        isSearch = true
    }
}